from django.shortcuts import render
from django_redis import get_redis_connection
from rest_framework.generics import ListAPIView, CreateAPIView
from rest_framework.response import Response
from rest_framework.filters import OrderingFilter

from goods.models import GoodsCategory, SKU
from goods.serializers import CategoriesSerializer, SKUHistorySerializer
from drf_haystack.viewsets import HaystackViewSet
from .serializers import SKUIndexSerializer

# Create your views here.
from rest_framework.views import APIView

from goods.utils import PageNum


class CategoriesView(APIView):
    """获取分类信息"""

    def get(self, request, pk):
        cat3 = GoodsCategory.objects.get(id=pk)
        # 通过三级获取一级和二级
        cat2 = cat3.parent
        cat1 = cat2.parent

        return Response({
            'cat1': cat1.name,
            'cat2': cat2.name,
            'cat3': cat3.name
        })


class CategoriesListView(ListAPIView):
    """获取商品列表页数据"""

    serializer_class = CategoriesSerializer

    # 分页属性
    pagination_class = PageNum
    # 排序属性
    filter_backends = [OrderingFilter]
    ordering_fields = ('create_time', 'sales', 'price')

    def get_queryset(self):

        pk = self.kwargs['pk']

        return SKU.objects.filter(category_id=pk)


class SKUSearchViewSet(HaystackViewSet):
    """
       SKU搜索
    """
    index_models = [SKU]

    serializer_class = SKUIndexSerializer

    pagination_class = PageNum


class SKUHistoryView(CreateAPIView):

    serializer_class = SKUHistorySerializer

    def get(self, request):

        # 1.获取用户对象
        user = request.user
        # 2.查询redis获取sku_id
        conn = get_redis_connection('history')
        sku_ids = conn.lrange('history_%s' % user.id, 0, 5)
        # 3.根据sku_id查询商品对象
        skus = SKU.objects.filter(id__in=sku_ids)
        # 4.序列化返回商品信息
        ser = CategoriesSerializer(skus, many=True)

        return Response(ser.data)